<template>
  <div class="dynamic-data-analysis" v-loading="loading" loading-text="加载数据中...">
    <div class="filter-container">
      <CustomDatePicker v-model="dateRange" :max-days="4" :disabled="loading"></CustomDatePicker>
      <el-button @click="handleReset" type="danger" :disabled="loading">重置</el-button>
    </div>
    <BaseChart ref="chart" :options="chartOption"></BaseChart>
  </div>
</template>

<script setup>
import { getMeterDetailApi } from '@/api/meter';
import BaseChart from '@/components/chart/BaseChart.vue';
import { watchEffect, ref, computed } from 'vue'
import dayjs from 'dayjs'
import CustomDatePicker from '@/components/header/CustomDatePicker.vue';

let loading = ref(false)
let chart = ref(null)

let props = defineProps({
  currentMeter: {
    type: Object,
    required: true
  }
})

// 时间范围
const defautTimeRange = [
  dayjs().subtract(2, 'day').startOf('day').valueOf(),
  dayjs().subtract(5, 'minute').valueOf()
];
const dateRange = ref(defautTimeRange);

let meterData = ref([])
const chartOption = computed(() => {
  return {
    title: "",
    xAxisData: meterData.value.map(item => item.time),
    yAxisUnit: "m³",
    series: [{
      name: "流量",
      type: 'line',
      data: meterData.value.map(item => item.value),
      showExtremum: true
    }],
    showMarkLine: true,
    iszoom: true,
    isMerge: false,
  }
})

const fetchMeterData = async () => {
  if (!props.currentMeter?.id) return

  loading.value = true
  try {
    let res = await getMeterDetailApi({
      id: props.currentMeter.id,
      start_time: dateRange.value[0],
      end_time: dateRange.value[1],
    })

    if (res.code !== 200) {
      ElMessage.error(res.message || '动态数据分析失败')
      console.error(res)
      return
    }

    // 确保数据按时间顺序排列
    res.meter_readings.sort((a, b) => new Date(a.time) - new Date(b.time));

    meterData.value = res.meter_readings
      .map((item, index) => {
        const prevValue = index === 0 ? item.value : res.meter_readings[index - 1].value
        return {
          value: calculateUsage(prevValue, item.value).toFixed(2),
          time: dayjs(item.time).format('MM-DD HH:mm')
        }
      }).slice(1)

  } catch (error) {
    console.error(error)
    ElMessage.error('服务器异常，动态数据分析失败')
  } finally {
    loading.value = false
  }
}

// 假设这是您的计算用量函数
const calculateUsage = (prevValue, currentValue) => {
  // 如果是第一个值，返回0或其他默认值
  if (prevValue === undefined || prevValue === null) {
    return 0
  }
  // 计算使用量
  return currentValue - prevValue
}

function handleReset() {
  dateRange.value = defautTimeRange;
}

watchEffect(() => {
  if (props.currentMeter?.id) {
    fetchMeterData()
  }
})
</script>

<style scoped>
.dynamic-data-analysis {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.filter-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1.2rem;
  flex-shrink: 0;
}

:deep(.vxe-table) {
  flex: 1;
  overflow: auto;
}
</style>